package com.smbms.servlet;

import cn.hutool.core.util.ObjectUtil;
import com.smbms.pojo.User;
import com.smbms.service.user.UserServiceImpl;
import com.smbms.utils.Constant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description 描述
 * @Author 羽落陌殇
 * @Date 2021/7/16 17:14
 * @Version 1.0.0
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取用户名和密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");
        String path = req.getContextPath();
        // 调用Service中的方法处理业务逻辑
        User loginUser = new UserServiceImpl().login(userCode, userPassword);
        if (ObjectUtil.isNotNull(loginUser)) {
            // 将用户数据存储到 Session 中
            req.getSession().setAttribute(Constant.USER_SESSION, loginUser);
            // 跳转到主页
            resp.sendRedirect(path + "/jsp/frame.jsp");
        } else {
            req.setAttribute("error", "用户名或者密码不正确, 请重新输入");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
